<template>
	<view>
		<view class="topBack" @click="backTop()">
			<u--image src="https://www.tdtye.com/files/vegetable_mall_file/default/backTop.png" width="70rpx"
				height="70rpx"></u--image>
		</view>
		<view style="position: relative;top: -20rpx">
			<uni-section type="line" title="图文相关">
			</uni-section>
			<view style="margin: 0 20rpx">
				<u--form labelPosition="left" :model="goods" labelWidth="auto">
					<u-form-item label="商品标题  " borderBottom>
						<u--textarea v-model="goods.title" placeholder="输入商品标题" clearable autoHeight border="none"
							maxlength="30" count="true">
						</u--textarea>
					</u-form-item>

					<u-form-item label="商品分类  " borderBottom @click="options.goodsCategory.show = true">
						<u-tag class="my-tag" :text=goods.category.name plain
							v-show="!check.isNull(goods.category.name)" @click="options.goodsCategory.show = true">
						</u-tag>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>

					<u-form-item label="商品简介  " borderBottom>
						<u--textarea v-model="goods.overview" placeholder="商品简介" clearable autoHeight border="none"
							maxlength="255" count="true">
						</u--textarea>
					</u-form-item>

					<!-- <u-form-item label="上传图片 " borderBottom>
						<uni-file-picker ref="avatarFile" fileMediatype="image" mode="grid"
							@select="goods.avatar.select" @delete="goods.avatar.delete" :image-styles="upload.style"
							limit="1" v-model="goods.avatar.list">
							<u-icon name="photo" color="#42535f" size="40"></u-icon>
						</uni-file-picker>
					</u-form-item> -->

					<u-form-item label="上传图片" borderBottom>
						<uni-file-picker ref="imgFile" fileMediatype="image" mode="grid" @select="goods.img.select"
							@delete="goods.img.delete" :image-styles="upload.style" limit="5" v-model="goods.img.list">
							<u-icon name="photo" color="#42535f" size="40"></u-icon>
						</uni-file-picker>
					</u-form-item>

					<u-form-item label="详情描述 " borderBottom>
						<u-button type="success" shape="circle" plain text="打开编辑窗" @click="editor.open">
						</u-button>
					</u-form-item>

					<u-form-item label="商品视频" borderBottom>
						<view>
							<video v-if="!check.isNull(goods.video.url)" style="width: 100px;
                  height: 100px;
                  display: inline-block;
                  " id="myVideo" :src=goods.video.url :enable-danmu="false" :danmu-btn="false" :direction="0" controls>
							</video>
							<view style="width: 200px;display: inline-block;margin-left: 15px">
								<uni-file-picker limit="1" fileMediatype="video" mode="list"
									@select="goods.video.select" @delete="goods.video.reDefault">
									<u-button>
										{{ check.isNull(goods.video.url) ? goods.video.text1 : goods.video.text2 }}
									</u-button>
								</uni-file-picker>
							</view>

						</view>
					</u-form-item>
				</u--form>
			</view>

			<uni-section type="line" title="地址相关">
			</uni-section>
			<view style="margin: 0 20rpx">
				<u--form labelPosition="left" :model="goods" labelWidth="auto">
					<u-form-item label="区域限购开关">
						<u-switch v-model="goods.limitArea.has" :activeValue=1 :inactiveValue=-1
							@change="options.limitArea.switchChange">
						</u-switch>
					</u-form-item>

					<view v-show="goods.limitArea.has === 1">
						<u-form-item>
							<view style="margin-bottom: 10px">
								<u--textarea v-model="goods.limitArea.selectText" autoHeight disabled border="surround">
								</u--textarea>
							</view>
							<u-button type="success" shape="circle" plain v-show="goods.limitArea.has === 1"
								@click="options.limitArea.open()">
								点击编辑限购区域
							</u-button>
						</u-form-item>
					</view>


					<u-divider />

					<u-form-item label="提货方式:">
						<uni-data-checkbox multiple v-model="options.type.result" :localdata="options.type.list"
							@change="options.type.change">
						</uni-data-checkbox>
					</u-form-item>

					<view v-show="goods.type.includes('1') || goods.type === '2'">
						<u-form-item label="是否包邮:">
							<u-switch v-model="goods.hasFreeShipp" :activeValue=1 :inactiveValue=-1>
							</u-switch>
						</u-form-item>
					</view>

					<view v-show="goods.hasFreeShipp === -1 && (goods.type.includes('1') || goods.type === '2')">
						<u-form-item label="运费模板:">
							<u-tag class="my-tag" :text=options.freightTemplate.selectText plain
								@click="options.freightTemplate.show = true">
							</u-tag>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
					</view>

					<view v-show="goods.type.includes('3') || goods.type === '2'">
						<u-divider text="支持配送地址" />
						<view style="margin: 10px 0">
							<u--textarea v-model="goods.locationIds.selectText" autoHeight disabled border="surround">
							</u--textarea>
						</view>
						<u-button type="success" shape="circle" plain @click="options.locationIds.open()">
							点击编辑支持配送的地址
						</u-button>
					</view>

					<view v-show="goods.type.includes('0') || goods.type === '2'">
						<u-divider text="自提地址" />
						<view style="margin: 10px 0">
							<u--textarea v-model="goods.selfMentionAddress.text" autoHeight disabled border="surround">
							</u--textarea>
						</view>
						<u-button type="success" shape="circle" plain @click="goods.selfMentionAddress.openMap()">
							点击定位商品自提地址
						</u-button>
					</view>

				</u--form>
			</view>

			<uni-section type="line" title="售卖相关">
			</uni-section>
			<view style="margin: 0 20rpx">
				<u--form labelPosition="left" :model="goods" labelWidth="auto">
					<u-form-item label="商品原价(单位/元) :" borderBottom>
						<u--input v-model="goods.originalPrice" type="digit" placeholder="输入商品原价">
						</u--input>
					</u-form-item>

					<u-form-item label="商品售卖单位(例:斤,件,盒) :" borderBottom>
						<u--input placeholder="输入售卖单位" v-model="goods.unit" clearable maxlength="10" />
					</u-form-item>

					<u-form-item label="商品库存(-1为无限库存) :" borderBottom>
						<u-number-box v-model="goods.inventory" :step="1" :min="-1" :max="999999" bgColor="#ffffff"
							inputWidth="80px">
						</u-number-box>
					</u-form-item>

					<u-form-item label="提供固定购买数量选项 :">
						<u-switch v-model="goods.buyUnit.open">
						</u-switch>
					</u-form-item>

					<view v-show="goods.buyUnit.open">
						<u-divider text="购买数量选项" />
						<view style="margin: 5px 0">
							<view
								:style="{width: 40 + item.toString().length * 7 + 'px', margin: '2px', display: 'inline-block'}"
								v-for="(item,index) in goods.buyUnit.value" :key="index">
								<u-tag :text="item" plain plainFill closable @close="goods.buyUnit.remove(item)">
								</u-tag>
							</view>

						</view>
						<view>
							<u-row gutter="10">
								<u-col span="6">
									<u-number-box inputWidth="100" v-model="goods.buyUnit.cache" :step="1" :min="1"
										bgColor="#ffffff" integer>
									</u-number-box>
								</u-col>
								<u-col span="6">
									<u-button type="primary" plain shape="circle" @click="goods.buyUnit.add()">
										<text style="font-size: 17px">添加</text>
									</u-button>
								</u-col>
							</u-row>
						</view>
					</view>

				</u--form>
			</view>

			<uni-section type="line" title="团购相关">
			</uni-section>
			<view style="margin: 0 20rpx">
				<u--form labelPosition="left" :model="goods" labelWidth="auto">
					<u-form-item label="推广佣金(单笔成交 单位/元)：" borderBottom>
						<u--input v-model="goods.commission" type="digit" placeholder="输入推广佣金">
						</u--input>
					</u-form-item>

					<u-form-item label="拼团时间 :">
						<uni-datetime-picker hide-second="true" type="datetimerange" v-model="goods.time.value"
							@change="goods.time.change" rangeSeparator="至" />
					</u-form-item>

					<u-form-item label="拼团是否自动续期 :">
						<u-switch v-model="goods.isAutoShelving" :activeValue=1 :inactiveValue=-1>
						</u-switch>
					</u-form-item>

					<view v-show="goods.isAutoShelving === 1">
						<u-form-item label="续期时间(单位/小时) :">
							<u--input v-model="goods.autoShelvingTime" type="digit" placeholder="输入续期时间">
							</u--input>
						</u-form-item>
					</view>

					<u-line></u-line>
					<u-form-item label="是否按规格定制优惠 :">
						<u-switch v-model="goods.spec.has" :activeValue=1 :inactiveValue=-1>
						</u-switch>
					</u-form-item>

					<view v-show="goods.spec.has === -1">

						<view>
							<u-divider text="优惠挡位列表" />
							<u-collapse :border=false :value="['test']">
								<view style="margin-top: 20rpx" v-for="(item,index) in goods.spec.nList" :key="index">
									<u-row>
										<u-col span="11">
											<u-collapse-item name="test" :border=false duration="500" :title="'用户购买数量达到 ' + item.successGear
                          + ' 每' + goods.unit + '单价 '
                          + item.discountPrice + ' 元'">
												<view>
													<view style="display: inline-block">
														<text style="color: #f54326">用户购买数量达到</text>
													</view>
													<view style="display: inline-block;margin-left: 20rpx">
														<u-number-box v-model="item.successGear" :step="1" :min="1"
															bgColor="#ffffff" inputWidth="70px"></u-number-box>
													</view>
													<view style="display: inline-block;margin-left: 20rpx">
														<text style="color: #f54326">{{ goods.unit }}</text>
													</view>
												</view>

												<view style="margin: 10px 0">
													<view style="display: inline-block">
														<text style="color: #f54326">每{{ goods.unit }}单价</text>
													</view>
													<view style="display: inline-block;margin-left: 20rpx">
														<u--input v-model="item.discountPrice" type="digit"
															placeholder="请输入优惠价格">
														</u--input>
													</view>
													<view style="display: inline-block;margin-left: 20rpx">
														<text style="color: #f54326">元</text>
													</view>
												</view>
											</u-collapse-item>
										</u-col>
										<u-col span="1">
											<u-button type="primary" plain shape="circle" icon="trash-fill"
												@click="goods.spec.removeNList(index)">
											</u-button>
										</u-col>
									</u-row>
								</view>

							</u-collapse>
						</view>
						<view>
							<u-form-item label="添加无规格优惠方案:">
								<u-button @click="goods.spec.addNList()" type="success" :text="btnText" plain
									shape="circle">
								</u-button>
							</u-form-item>
						</view>
					</view>

					<view v-show="goods.spec.has === 1">
						<view>
							<u-divider text="优惠挡位列表" />
							<u-collapse :border="false" :value="['test']">
								<view style="margin-top: 20rpx" v-for="(item,index) in goods.spec.yList" :key="index">
									<u-row>
										<u-col span="11">
											<u-collapse-item name="test" :border="false" duration="500"
												:title="'规格名称 :' + item.specName+ '  /  原价 : ' + item.originalPrice + ' 元'+ '  /  库存 : ' + item.inventory">
												<u--form :model="item" labelPosition="left" labelWidth="auto">
													<u-form-item label="规格名称 :" borderBottom>
														<u--textarea placeholder="请输入规格名称" v-model="item.specName"
															autoHeight border="none" maxlength="100" count="true" />
													</u-form-item>

													<u-form-item label="原价(单位/元) :" borderBottom>
														<u--input v-model="item.originalPrice" type="digit"
															placeholder="输入商品原价">
														</u--input>
													</u-form-item>

													<u-form-item label="库存(-1为无限库存) :" borderBottom>
														<u-number-box v-model="item.inventory" :step="1" :min="-1"
															:max="999999" bgColor="#ffffff" inputWidth="80px">
														</u-number-box>
													</u-form-item>


												</u--form>
												<scroll-view scroll-y="true" style="height: 500rpx;">
													<view style="margin-top: 5rpx"
														v-for="(item2,index2) in item.priceGear" :key="index2">
														<u-row>
															<u-col span="11">
																<view>
																	<view style="display: inline-block">
																		<text style="color: #f54326">用户购买数量达到</text>
																	</view>
																	<view
																		style="display: inline-block;margin-left: 20rpx">
																		<u-number-box v-model="item2.successGear"
																			:step="1" :min="1" bgColor="#ffffff"
																			inputWidth="70px"></u-number-box>
																	</view>
																	<view
																		style="display: inline-block;margin-left: 20rpx">
																		<text style="color: #f54326">{{ goods.unit }}
																		</text>
																	</view>
																</view>

																<view style="margin: 10px 0">
																	<view style="display: inline-block">
																		<text style="color: #f54326">每{{ goods.unit }}单价
																		</text>
																	</view>
																	<view
																		style="display: inline-block;margin-left: 20rpx;width: 250rpx;">
																		<u--input v-model="item2.discountPrice"
																			type="digit" placeholder="请输入优惠价格">
																		</u--input>
																	</view>
																	<view
																		style="display: inline-block;margin-left: 20rpx">
																		<text style="color: #f54326">元</text>
																	</view>
																</view>
															</u-col>
															<u-col span="1">
																<view style="margin-left: -90rpx;margin-top: 90rpx;">
																	<u-button type="warning" plain shape="circle"
																		icon="trash-fill"
																		@click="goods.spec.removeYListGear(index,index2)">
																	</u-button>
																</view>
															</u-col>
														</u-row>
													</view>

												</scroll-view>
												<u-form-item borderBottom>
													<u-button type="success" shape="circle" :text="btnText"
														@click="goods.spec.addYListGear(index)">
													</u-button>
												</u-form-item>
											</u-collapse-item>
										</u-col>
										<u-col span="1">
											<u-button type="primary" plain shape="circle" icon="trash-fill"
												@click="goods.spec.removeYList(index)">
											</u-button>
										</u-col>
									</u-row>
								</view>

							</u-collapse>
						</view>
						<view>
							<u-form-item label="添加有规格优惠方案:">
								<u-button type="success" :text="btnTextSpec" plain shape="circle"
									@click="goods.spec.addYList()">
								</u-button>
							</u-form-item>
						</view>
					</view>

				</u--form>
			</view>

			<view>
				<view style="margin: 10px">
					<u-button type="primary" shape="circle" @click="commit">
						<text style="font-size: 18px;font-weight: bold">提 交</text>
					</u-button>
				</view>
			</view>

			<!--非主动显示的组件 -->
			<view>
				<!--商品分类选择器-->
				<u-picker :show="options.goodsCategory.show" :columns="options.goodsCategory.ops"
					@confirm="options.goodsCategory.confirm" @close="options.goodsCategory.close"
					@cancel="options.goodsCategory.cancel" closeOnClickOverlay="true" title="选择商品分类" keyName="name">
				</u-picker>

				<!--运费模板选择器-->
				<u-picker :show="options.freightTemplate.show" :columns="options.freightTemplate.ops"
					@confirm="options.freightTemplate.confirm" @close="options.freightTemplate.close"
					@cancel="options.freightTemplate.cancel" closeOnClickOverlay="true" title="选择运费模板" keyName="remark">
				</u-picker>

				<!--自己封装的提示器-->
				<popup ref="popup" />

				<!--富文本-->
				<view>
					<uni-drawer ref="showEditor" mode="left" width="410" :maskClick=false>
						<view>
							<robin-editor ref="editor" class="editor" v-model="editor.context" muiltImage="true"
								compressImage="false" :imageUploader="editorUploadImg" @cancel="editor.cancel"
								@save="editor.save" @setUrlId="setUrlId" hint="用文字描述一下您的宝贝商品吧,您可以选择继续添加或者不添加图片(就算这里不添加图片,外面上传的图片也会直接展示在详情处哦)">
							</robin-editor>
						</view>
					</uni-drawer>
				</view>

			</view>

			<!--选择限购地址-->
			<BaTreePicker ref="limitArea" :multiple=true title="编辑限购地区" valueKey="id" textKey="name"
				childrenKey="subList" @select-change="options.limitArea.ok" />

			<!--选择支持配送的地址-->
			<BaTreePicker ref="locationIds" :multiple=true title="编辑支持配送的地址" valueKey="id" textKey="name"
				childrenKey="subList" @select-change="options.locationIds.ok" />

			<u-modal :show="modal.byStatus.show" :title="modal.byStatus.title" :confirmText="modal.byStatus.confirmText"
				@confirm="modal.byStatus.confirm">
				<view>
					<rich-text :nodes="modal.byStatus.content"></rich-text>
				</view>
			</u-modal>

		</view>
	</view>


</template>

<script>
	import service from "../../../utils/service";
	import {
		pathToBase64
	} from "@/js_sdk/mmmm-image-tools/index";
	import popup from "@/merchant/my/my-popup"
	import USwitch from "../../../uni_modules/uview-ui/components/u-switch/u-switch";
	import BaTreePicker from "@/merchant/comm/ba-tree-picker/ba-tree-picker"
	import URow from "../../../uni_modules/uview-ui/components/u-row/u-row";
	import UCol from "../../../uni_modules/uview-ui/components/u-col/u-col";

	export default {
		components: {
			UCol,
			URow,
			USwitch,
			popup,
			BaTreePicker,
		},
		data() {
			let _vm = this;
			return {
				iconStyle: {
					fontSize: '32rpx',
					color: '#fff',
				},
				scrollTop: 0,
				btnTextSpec: "添加规格",
				btnText: "添加优惠档位",
				// 页面目标 add 为添加商品 update 为 修改商品
				target: 'add',
				routerV: {},
				// 比较工具封装
				check: service.check,
				/* 商品对象 */
				goods: {
					id: '',
					/*商品标题*/
					title: '',
					/*分类*/
					category: {
						name: '',
						id: '',
					},
					/*商品简介*/
					overview: '',
					/*商品主图*/
					avatar: {
						//页面显示用 元素 {url: '',base64: ''}
						list: [],
						reDefault() {
							this.list = [];
						},
						// 选中图像
						select(e) {
							let _t = this;
							let avatar = this.goods.avatar;
							console.log('选择商品主图 ：', e);
							let size = 10;
							if (service.check.fileSizeOutBounds(e.tempFiles, size)) {
								_t.$refs.popup.error('不能上传超过 ' + size + ' M 的图像')
								// 清空
								_t.$refs.avatarFile.clearFiles(0);
								avatar.reDefault();
								return
							}
							pathToBase64(e.tempFilePaths[0]).then(res => {
								avatar.list.push({
									url: e.tempFilePaths[0],
									base64: res
								});
							});
						},
						// 删除选中头像
						delete(e) {
							console.log("删除商品主图 :", e)
							this.goods.avatar.reDefault();
						}
					},
					/*商品轮播图*/
					img: {
						// 页面显示用 元素: {url: '',base64:''}
						list: [],
						// 轮播图选中
						select(e) {
							let _t = this;
							let img = this.goods.img;
							console.log("选中轮播图 : ", e)
							let size = 10;
							if (service.check.fileSizeOutBounds(e.tempFiles, size)) {
								_t.$refs.popup.error('不能上传超过 ' + size + ' M 的图像')
								// 删除显示图片的下标为 当前列表的长度 即 即将添加的图片下标
								_t.$refs.imgFile.clearFiles(img.list.length);
								return
							}
							// 解析成 base 64 添加到列表中
							e.tempFilePaths.forEach(e => {
								pathToBase64(e).then(res => {
									img.list.push({
										url: e,
										base64: res
									})
								});
							})
							console.log("选中后的图像列表 : ", img.list)
						},
						// 轮播图删除
						delete(e) {
							let _t = this;
							let img = this.goods.img;
							console.log("即将删除的轮播图 :", e)
							console.log("即将操作的轮播图列表 : ", img.list)
							// 得到将要删除的图像 url
							let delUrl = e.tempFilePath;
							// 得到需要删除的下标
							let index = img.list.findIndex(v => {
								return delUrl === v.url;
							})
							console.log("即将删除的轮播图下标 : ", index)
							img.list.splice(index, 1);
							console.log("删除后的轮播列表: ", img.list)
						}
					},
					/*商品详情 富文本*/
					content: '',
					/*限购区域对象*/
					limitArea: {
						idList: [],
						// 是否有限购区域 -1 没有 1 有
						has: -1,
						selectText: '',
					},
					/*运费分类*/
					type: "",
					/*是否包邮*/
					hasFreeShipp: -1,
					/*模板id*/
					freightId: -1,
					/*支持配送区域对象*/
					locationIds: {
						list: [],
						selectText: '',
					},
					/*自提地址*/
					selfMentionAddress: {
						/*文本内容*/
						text: '',
						/*纬度*/
						lat: '',
						/*经度*/
						lng: '',
						/* 打开地图选择自提地址 */
						openMap() {
							uni.chooseLocation({
								latitude: _vm.goods.selfMentionAddress.lat,
								longitude: _vm.goods.selfMentionAddress.lng,
								success: res => {
									console.log("自提地址选中 : ", res)
									if (service.check.isNull(res.address)) {
										_vm.$refs.popup.error("请定位后选择下方中其中一个地址点击确定,进行有效定位")
										return
									}
									_vm.goods.selfMentionAddress.text = res.address;
									_vm.goods.selfMentionAddress.lat = res.latitude;
									_vm.goods.selfMentionAddress.lng = res.longitude;
								}
							})
						}
					},
					/*商品视频*/
					video: {
						text1: '上传视频',
						text2: '重新上传',
						url: '',
						hasUpdate: false,
						reDefault() {
							_vm.goods.video.url = '';
							_vm.goods.video.hasUpdate = true;
						},
						// 选中文件
						select(v) {
							console.log("选中文件 : ", v)
							if (service.check.fileSizeOutBounds(v.tempFiles, 50)) {
								_vm.$refs.popup.error("上传视频文件大小不能超过 50 M")
								return
							}
							_vm.goods.video.url = v.tempFilePaths[0]
							_vm.goods.video.hasUpdate = true;
						}
					},
					/*商品原价*/
					originalPrice: 1,
					/*商品库存*/
					inventory: -1,
					/*商品单位*/
					unit: '',
					/*可选购买数量*/
					buyUnit: {
						/* 是否开启 */
						open: false,
						value: [],
						/* 添加缓存字符 */
						cache: 1,
						add() {
							console.log("添加购买数量 : ", _vm.goods.buyUnit.cache)
							if (_vm.check.isNull(_vm.goods.buyUnit.cache)) {
								_vm.$refs.popup.error("请输入购买数量再添加")
								return
							}
							if (_vm.goods.buyUnit.value.some(e => _vm.goods.buyUnit.cache === e)) {
								_vm.$refs.popup.error("不能添加相同的购买数量")
								return
							}
							_vm.goods.buyUnit.value.push(_vm.goods.buyUnit.cache)
							_vm.goods.buyUnit.value.sort((a, b) => a - b)
							console.log("数组 : ", _vm.goods.buyUnit.value)
						},
						remove(v) {
							console.log("即将删除的购买数量 : ", v)
							let index = _vm.goods.buyUnit.value.findIndex(e => e === v)
							if (index !== -1) {
								_vm.goods.buyUnit.value.splice(index, 1)
							}
						},
					},
					/* 推广佣金 */
					commission: 0,
					/*售卖规格*/
					spec: {
						// 是否有规格 -1 没有 1 有
						has: -1,
						// 有规格优惠列表
						yList: [],
						// 无规格优惠列表
						nList: [],
						// 添加无规格优惠列表
						addNList() {
							_vm.goods.spec.nList.splice(0, 0, {
								successGear: 1,
								discountPrice: 1
							})
							_vm.btnText = "继续添加优惠档位"
						},
						// 删除无规格优惠列表
						removeNList(index) {
							_vm.goods.spec.nList.splice(index, 1)
						},
						// 添加规格
						addYList() {
							_vm.goods.spec.yList.splice(0, 0, {
								specName: '请填写',
								originalPrice: 1,
								inventory: -1,
								priceGear: [{
									successGear: 1,
									discountPrice: 1
								}]
							})
							_vm.btnTextSpec = "继续添加规格"
						},
						// 添加规格优惠列表 index 为当前优惠列表的规格下标
						addYListGear(index) {
							console.log(_vm.goods.spec.yList[index])
							_vm.goods.spec.yList[index].priceGear.splice(0, 0, {
								successGear: 1,
								discountPrice: 1
							})
							_vm.goods.spec.yList[index].priceGear = service.copy(_vm.goods.spec.yList[index].priceGear);
							_vm.btnText = "继续添加优惠档位"
						},
						// 删除规格 index 规格下标
						removeYList(index) {
							_vm.goods.spec.yList.splice(index, 1)
						},
						// 删除规格优惠列表 i: 规格下标 j: 优惠列表下标
						removeYListGear(i, j) {
							_vm.goods.spec.yList[i].priceGear.splice(j, 1)
						}
					},
					/* 静态资源路径id */
					urlId: '',
					/* 拼团时间 */
					time: {
						/*0 开始时间 1 结束时间*/
						value: [],
						change(e) {
							console.log("选择拼团时间 : ", e)
						}
					},
					/* 是否自动续期 */
					isAutoShelving: -1,
					/* 续期时间(小时) */
					autoShelvingTime: '',
				},
				/* 选项相关对象 */
				options: {
					/*商品分类*/
					goodsCategory: {
						show: false,
						ops: [
							[]
						],
						confirm(v) {
							// console.log("商品分类选项 : ",v)
							this.options.goodsCategory.show = false;
							this.goods.category.id = v.value[0].id;
							this.goods.category.name = v.value[0].name;
						},
						close() {
							this.options.goodsCategory.show = false;
						},
						cancel() {
							this.options.goodsCategory.show = false;
						}
					},
					/*限购区域*/
					limitArea: {
						ops: [],
						switchChange(v) {
							if (v === 1) {
								console.log("打开限购区域开关 : ", v)
							}
						},
						ok(values, names) {
							console.log("选中限购地址 :")
							console.log("ids : ", values, names)
							_vm.goods.limitArea.selectText = names;
							if (values.length === 0) {
								_vm.goods.locationIds.selectText = '';
								_vm.goods.locationIds.list = [];
								return
							}
							_vm.getSubIdListByParentId(values, {
								ok: function(v) {
									_vm.goods.limitArea.idList = v;
									_vm.$refs.limitArea.setSelectedData(
										service.copy(_vm.goods.limitArea.idList))
								}
							})
						},
						open() {
							_vm.$refs.limitArea._show();
						}
					},
					/*运费分类*/
					type: {
						list: [{
								text: '自提',
								value: 0,
								disabled: false
							},
							{
								text: '快递',
								value: 1,
								disabled: false
							},
							{
								text: '配送',
								value: 3,
								disabled: false
							},
						],
						result: [],
						change(v) {
							console.log("提货方式选项改变 : ", v)
							let arr = v.detail.value;
							// 如果全选则为 2 如果非全选 则为 编号逆序
							if (_vm.options.type.result.length === 3) {
								_vm.goods.type = '2';
								return
							}
							arr.sort((a, b) => a - b)
							arr.reverse();
							_vm.goods.type = arr.toString().replaceAll(",", '');
							console.log(_vm.goods.type)
						},
					},
					/*运费模板*/
					freightTemplate: {
						show: false,
						selectText: '点击选择运费模板',
						ops: [
							[]
						],
						confirm(v) {
							console.log("选择运费模板 : ", v)
							this.options.freightTemplate.show = false;
							this.goods.freightId = v.value[0].id
							this.options.freightTemplate.selectText = v.value[0].remark
						},
						close() {
							this.options.freightTemplate.show = false;
						},
						cancel() {
							this.options.freightTemplate.show = false;
						}
					},
					/* 支持配送的地址 */
					locationIds: {
						ops: [],
						ok(values, names) {
							console.log("选中支持配送地址 :")
							console.log("ids : ", values, names)
							_vm.goods.locationIds.selectText = names;
							if (values.length === 0) {
								_vm.goods.locationIds.selectText = '';
								_vm.goods.locationIds.list = [];
								return
							}
							_vm.getSubIdListByParentId(values, {
								ok: function(v) {
									_vm.goods.locationIds.list = v;
									_vm.$refs.locationIds.setSelectedData(
										service.copy(_vm.goods.locationIds.list))
								}
							})
						},
						open() {
							_vm.$refs.locationIds._show();
						}
					},
				},
				/* 文件上传相关对象 */
				upload: {
					style: {
						"height": 80, // 边框高度
						"width": 80, // 边框宽度
						"border": { // 如果为 Boolean 值，可以控制边框显示与否
							"color": "#3646505e", // 边框颜色
							"width": "3px", // 边框宽度
							"style": "solid", // 边框样式
						},
					},
				},
				/* 加载对象 */
				loading: {
					// 取消加载 true
					flag: false,
					// 进度
					plan: 0,
					// 阈值
					threshold: 0,
					step() {
						if (++this.plan >= this.threshold) {
							try {
								// 如果分类id != 空字符 那么表示是需要回显分类选项
								if (_vm.goods.category.id !== '') {
									console.log("分类选项 : ", _vm.options.goodsCategory.ops[0]);
									// 得到分类对象
									let item = _vm.options.goodsCategory.ops[0].find(e => {
										return e.id === _vm.goods.category.id;
									})
									if (!_vm.check.isNull(item)) {
										_vm.goods.category.name = item.name;
									}
								}
								// 如果该商品有运费模板
								if (_vm.goods.freightId !== -1) {
									let item = _vm.options.freightTemplate.ops[0].find(e => {
										return e.id === _vm.goods.freightId;
									})
									if (!_vm.check.isNull(item)) {
										_vm.options.freightTemplate.selectText = item.remark;
									}
								}
								if (_vm.goods.type === '2' || _vm.goods.type.includes('3')) {
									_vm.$refs.locationIds.setSelectedData(
										service.copy(_vm.goods.locationIds.list))
								}
								if (_vm.goods.limitArea.has === 1) {
									_vm.$refs.limitArea.setSelectedData(
										service.copy(_vm.goods.limitArea.idList))
								}
								if (_vm.goods.status === 0) {
									_vm.modal.byStatus.open();
								}
							} catch (e) {
								console.log(" loading.step() err :  ", e)
							} finally {
								uni.hideLoading();
							}
						}
					}
				},
				/* 富文本对象 */
				editor: {
					// 空文本展位
					placeholder: '请输入商品详情',
					// 富文本内容
					context: '',
					// 富文本临时内容
					tempText: '',
					// 初始值
					initial: "<p><br></p>",
					open() {
						this.$refs.showEditor.open()
					},
					save(e) {
						console.log("富文本保存事件 : ", e)
						// 如果跟初始值一致则不进行赋值
						if (e.html !== _vm.editor.initial) {
							_vm.editor.context = service.copy(e.html)
							_vm.goods.content = service.copy(e.html)
						}
						_vm.editor.close();
					},
					// 取消则测回修改
					cancel(e) {
						_vm.editor.close();
					},
					close() {
						_vm.$refs.showEditor.close()
					},
				},

				/* 模态窗对象 */
				modal: {
					/* 根据团购商品状态  */
					byStatus: {
						show: false,
						title: '注意',
						confirmText: '知道了',
						content: '<span>当前团购正在进行中,修改内容仅对 : ' +
							' [ <span style="color:#ff4757"> 商品库存,标题,简介,详情页,主图,轮播图,视频 </span> ] ' +
							'生效,对其他参数不会生效,如需修改请 <span style="color:#ff6b81">先下架商品.</span>' +
							'</span>',
						open() {
							_vm.modal.byStatus.show = true
						},
						confirm() {
							_vm.modal.byStatus.close();
						},
						cancel() {
							_vm.modal.byStatus.close();
						},
						close() {
							_vm.modal.byStatus.show = false
						},
					}
				}
			}
		},
		methods: {
			backTop() {
				uni.pageScrollTo({
					scrollTop: 0
				})
			},
			/*设置资源路径id*/
			setUrlId(v) {
				this.goods.urlId = v;
			},
			/* 富文本上传图像 */
			editorUploadImg(path, callback, _t = this) {
				// 获取图像地址前缀
				let imgApi = this.$reqConfig.URLIMAGE
				// 获取请求头类型
				this.contentType = this.$reqConfig.CONTENTTYPE + ";+charset=UTF-8"
				// 获取token
				this.token = uni.getStorageSync("merchantsToken").token
				uni.uploadFile({
					url: this.$reqConfig.UPLOADAPI + 'merchant/merchantGroupGoods/uploadImg',
					filePath: path,
					name: 'file',
					header: {
						"Authorization": this.token,
						"Content-type": this.contentType,
						"type": "merchantsToken"
					},
					success: res => {
						let result = JSON.parse(res.data);
						if (result.code === 0) {
							callback(imgApi + result.result.uploads[0])
							this.$emit('setUrlId', result.result.id)
						}
					},
				})
			},
			/* 获取团购商品分类选项 */
			getCategoryOptions() {
				let _t = this;
				this.$axios({
					url: 'system/sysCategory/listNoPage',
					method: 'post',
					data: {
						type: 3
					},
					header: {
						"Authorization": this.token,
						"Content-type": this.contentType,
						"type": "merchantsToken"
					},
				}).then(res => {
					console.log('system/sysCategory/listNoPage :', res)
					if (res.code === 0) {
						_t.options.goodsCategory.ops[0] = res.result;
					}
					//请求加载步进
					_t.loading.step();
				})
			},
			/* 获取团购商品详情信息 */
			getDetails(id) {
				let _t = this;
				this.$axios({
					url: 'merchant/merchantGroupGoods/detail',
					method: 'post',
					data: {
						id: id
					},
					header: {
						"Authorization": this.token,
						"Content-type": this.contentType,
						"type": "merchantsToken"
					},
				}).then(res => {
					console.log('merchant/merchantGroupGoods/detail : ', res);
					if (res.code === 0) {
						let resGoods = res.result.merchantGroupGoods;

						let errorFields = []

						//商品id
						_t.goods.id = resGoods.id;

						//商品标题
						_t.goods.title = resGoods.title;

						// 商品状态
						_t.goods.status = resGoods.status;

						// 解析头像
						_t.goods.avatar.list.push({
							url: _t.imgApi + resGoods.avatar,
							base64: ''
						})
						// 解析轮播图
						JSON.parse(resGoods.img).forEach(e => {
							_t.goods.img.list.push({
								url: _t.imgApi + e,
								base64: ''
							})
						})

						// 商品分类
						_t.goods.category.id = resGoods.categoryId;

						//商品简介
						_t.goods.overview = resGoods.overview;

						//商品详情(富文本)
						if (!resGoods.content.includes("style")) {
							resGoods.content = resGoods.content.replaceAll(/\<img/gi,
								'<img style="max-width:100%;height:auto"')
						}
						if (!resGoods.content.includes(_t.imgApi)) {
							resGoods.content = resGoods.content
								.replaceAll(/src="/gi, 'src=' + '\"' + _t.imgApi);
						}
						_t.goods.content = service.copy(resGoods.content);
						_t.editor.context = service.copy(resGoods.content);

						//运费分类
						let type = resGoods.type.toString();
						_t.goods.type = type;
						if (type === '2') {
							_t.options.type.result.push(0, 1, 3)
						} else {
							for (let i = 0; i < type.length; i++) {
								_t.options.type.result.push(parseInt(type.charAt(i)))
							}
						}

						// 是否包邮
						_t.goods.hasFreeShipp = resGoods.hasFreeShipp;

						// 模板id
						_t.goods.freightId = resGoods.freightId;

						// 支持配送地址
						if ((type === '2' || type.includes('3')) && !_t.check.isNull(resGoods.locationIds)) {
							let arr = resGoods.locationIds.split(',');
							for (let i = 0; i < arr.length; i++) {
								_t.goods.locationIds.list.push(parseInt(arr[i]))
							}
						}

						// 自提地址 以及经纬度
						if ((type === '2' || type.includes('0'))) {
							if (!_t.check.isNull(resGoods.selfMentionAddress)) {
								_t.goods.selfMentionAddress.text = resGoods.selfMentionAddress;
							}
							if (!_t.check.isNull(resGoods.latLng)) {
								let arr = resGoods.latLng.split(',');
								if (arr.length === 2) {
									_t.goods.selfMentionAddress.lat = arr[0]
									_t.goods.selfMentionAddress.lng = arr[1]
								}
							}
						}

						// 获取商品视频连接
						if (!_t.check.isNull(resGoods.video)) {
							_t.goods.video.url = _t.imgApi + resGoods.video
						}

						// 获取商品原价
						if (!_t.check.isNull(resGoods.originalPrice)) {
							_t.goods.originalPrice = resGoods.originalPrice;
						}

						// 商品库存
						_t.goods.inventory = resGoods.inventory;

						// 商品单位
						_t.goods.unit = resGoods.unit;

						// 商品购买单位
						if (!_t.check.isNull(resGoods.buyUnit)) {
							let arr = resGoods.buyUnit.split(",");
							if (arr.length !== 0) {
								_t.goods.buyUnit.open = true;
								// 字符 转 数字
								_t.goods.buyUnit.value = arr.map(e => e * 1);
							}
						}

						// 拼团时间
						_t.goods.time.value.push(resGoods.startTime);
						_t.goods.time.value.push(resGoods.endTime);

						// 拼团是否续期 , 续期时间
						service.executeTask(function() {
							_t.goods.isAutoShelving = resGoods.isAutoShelving;
						}, errorFields, "拼团是否续期")

						service.executeTask(function() {
							_t.goods.autoShelvingTime = resGoods.autoShelvingTime;
						}, errorFields, "续期时间")

						// 商品推广佣金
						if (!_t.check.isNull(resGoods.commission)) {
							_t.goods.commission = resGoods.commission;
						}

						// 得到商品快照
						let snapshot = JSON.parse(resGoods.snapshot);
						// 得到是否限购区域
						_t.goods.limitArea.has = resGoods.hasAreaLimit;
						// 有限购区域 则得到限购区域id
						if (_t.goods.limitArea.has === 1) {
							_t.goods.limitArea.idList = snapshot.areaList.split(",").map(e => {
								return parseInt(e)
							});
						}

						// 获取商品规格 以及 优惠列表
						_t.goods.spec.has = resGoods.hasSpec;
						if (resGoods.hasSpec === -1) {
							_t.goods.spec.nList = JSON.parse(snapshot.priceList);
						} else {
							_t.goods.spec.yList = JSON.parse(snapshot.priceList)
						}

						// 获取静态路径id
						_t.goods.urlId = resGoods.urlId

					}
					//请求加载步进
					_t.loading.step();
				})
			},
			/* 获取地址分类树信息 */
			getLocationTree() {
				let _t = this
				this.$axios({
					url: 'merchant/merchantGroupGoods/locationTree',
					method: 'post',
					header: {
						"Authorization": this.token,
						"Content-type": this.contentType,
						"type": "merchantsToken"
					},
				}).then(res => {
					if (res.code === 0) {
						_t.options.limitArea.ops = service.copy(res.result)
						_t.options.locationIds.ops = service.copy(res.result)
						_t.$refs.limitArea.setLocalData(_t.options.limitArea.ops)
						_t.$refs.locationIds.setLocalData(_t.options.locationIds.ops)
					}
					//请求加载步进
					_t.loading.step();
				})
			},
			/* 获取商家运费模板 */
			getMerchantFreightTemplate() {
				let _t = this;
				this.$axios({
					url: 'merchant/merchantFreightTemplate/list',
					method: 'post',
					data: {
						pageNo: 1,
						pageSize: 100
					},
					header: {
						"Authorization": this.token,
						"Content-type": this.contentType,
						"type": "merchantsToken"
					},
				}).then(res => {
					console.log('merchant/merchantFreightTemplate/list :', res)
					if (res.code === 0) {
						res.result.list.forEach(e => {
							_t.options.freightTemplate.ops[0].push({
								id: e.id,
								remark: e.remark
							})
						})
					}
					//请求加载步进
					_t.loading.step();
				})
			},
			/* 根据地址 父级 id列表 获取 最子级id*/
			getSubIdListByParentId(pIds, okBack) {
				let _t = this;
				this.$axios({
					url: 'system/sysLocation/getSubIdByPidList',
					method: 'post',
					data: {
						pIds: pIds
					}
				}).then(res => {
					console.log('system/sysLocation/getSubIdByPidList : ', res)
					if (res.code === 0) {
						okBack["ok"](res.result);
					} else {
						_t.$refs.popup.error(res.message);
					}
				})
			},
			/* 添加商品*/
			commit() {
				// 先校验参数
				if (this.checkParam()) {
					return;
				}
				uni.showLoading({
					title: '正在提交中....',
					mask: true
				});
				let _t = this;
				if (this.target === 'add') {
					if (!service.check.isNull(_t.goods.video.url) && _t.goods.video.hasUpdate) {
						uni.uploadFile({
							url: _t.$config.UPLOADAPI + 'merchant/merchantGroupGoods/addGroupGoods',
							filePath: _t.goods.video.url,
							name: 'video',
							formData: _t.getAddRequest(),
							header: {
								"Authorization": this.token,
								"Content-type": this.contentType,
								"type": "merchantsToken"
							},
							success: (res) => {
								console.log("merchant/merchantGroupGoods/addGroupGoods : ", JSON.parse(res
									.data));
								if (JSON.parse(res.data).code === 0) {
									_t.$refs.popup.success('添加商品成功');
									uni.navigateBack({
										delta: 1
									})
								} else {
									_t.$refs.popup.success('添加商品失败 : ' + JSON.parse(res.data).message);
								}
							},
							complete: (res) => {
								uni.hideLoading()
							}

						});
					} else {
						this.$axios({
							url: '/merchant/merchantGroupGoods/addGroupGoods',
							method: 'post',
							data: _t.getAddRequest(),
							header: {
								"Authorization": this.token,
								"Content-type": this.contentType,
								"type": "merchantsToken"
							},
						}).then(res => {
							console.log("/merchant/merchantGroupGoods/addGroupGoods : ", res);
							if (res.code === 0) {
								_t.$refs.popup.success('添加商品成功');
								uni.navigateBack({
									delta: 1
								})
							} else {
								_t.$refs.popup.success('添加商品失败 : ' + res.message);
							}
						}).finally(() => {
							uni.hideLoading()
						})
					}

				} else {
					this.update();
				}
			},
			/*修改商品*/
			update() {
				let _t = this
				if (!service.check.isNull(_t.goods.video.url) && _t.goods.video.hasUpdate) {
					uni.uploadFile({
						url: _t.$config.UPLOADAPI + 'merchant/merchantGroupGoods/updateGoods',
						filePath: _t.goods.video.url,
						name: 'video',
						formData: _t.getUpdateRequest(),
						header: {
							"Authorization": this.token,
							"Content-type": this.contentType,
							"type": "merchantsToken"
						},
						success: (res) => {
							console.log("merchant/merchantGroupGoods/updateGoods : ", JSON.parse(res.data));
							if (JSON.parse(res.data).code === 0) {
								_t.$refs.popup.success('修改商品成功');
								uni.navigateBack({
									delta: 1
								})
							} else {
								_t.$refs.popup.success('修改商品失败 : ' + JSON.parse(res.data).message);
							}
						},
						complete: (res) => {
							uni.hideLoading()
						}
					});
				} else {
					this.$axios({
						url: '/merchant/merchantGroupGoods/updateGoods',
						method: 'post',
						data: _t.getUpdateRequest(),
						header: {
							"Authorization": this.token,
							"Content-type": this.contentType,
							"type": "merchantsToken"
						},
					}).then(res => {
						console.log("merchant/merchantGroupGoods/updateGoods : ", res);
						if (res.code === 0) {
							_t.$refs.popup.success('修改商品成功');
							uni.navigateBack({
								delta: 1
							})
						} else {
							_t.$refs.popup.success('修改商品失败 : ' + res.message);
						}
					}).finally(() => {
						uni.hideLoading()
					})
				}

			},
			/*校验参数*/
			checkParam() {
				let goods = this.goods;
				let popupTemp = this.$refs.popup;
				if (service.check.isNull(goods.title)) {
					popupTemp.error("请填写商品标题");
					return true;
				}

				if (service.check.isNull(goods.category.id)) {
					popupTemp.error("请选择商品分类")
					return true;
				}

				if (service.check.isNull(goods.overview)) {
					popupTemp.error("请输入商品简介")
					return true
				}

				// if (goods.avatar.list.length === 0) {
				// 	popupTemp.error("请上传商品主图")
				// 	return true
				// }

				if (goods.img.list.length === 0) {
					popupTemp.error("请上传商品图片")
					return true
				}

				// if (service.check.isNull(goods.content) || service.check.isNull(this.editor.context)) {
				// 	popupTemp.error("请编写商品详情")
				// 	return true
				// }

				// 校验限购区域对象
				if (goods.limitArea.has === 1 && goods.limitArea.idList.length === 0) {
					popupTemp.error("请编辑商品的限购区域")
					return true
				}

				// 校验运费分类
				if (service.check.isNull(goods.type)) {
					popupTemp.error("请至少选择一项提货方式")
					return true
				}


				// 校验是否选择拼团时间
				if (goods.time.value.length !== 2) {
					popupTemp.error("请设定好拼团时间")
					return true
				}

				// 如果续期 校验 续期时间合法性
				if (goods.isAutoShelving === 1) {
					if (!service.check.isNumber(goods.autoShelvingTime) ||
						goods.autoShelvingTime <= 0) {
						popupTemp.error("自动续期时间必须是数字 , 且必须大于 0")
						return true
					}
				}

				// 如果支持快递 校验是否设置了运费模板
				if ((goods.type === '2' || goods.type.includes('1')) && goods.hasFreeShipp === -1 && goods.freightId === -
					1) {
					popupTemp.error("请选择运费模板")
					return true
				}

				// 如果支持配送 校验是否设置了支持配送的地址
				if ((goods.type === '2' || goods.type.includes('3')) && goods.locationIds.list.length === 0) {
					popupTemp.error("请选择商品支持配送的地址")
					return true
				}

				// 如果支持自提 校验是否设置了自提地址
				if ((goods.type === '2' || goods.type.includes('0'))) {
					if (service.check.isNull(goods.selfMentionAddress.lng) ||
						service.check.isNull(goods.selfMentionAddress.lat) ||
						service.check.isNull(goods.selfMentionAddress.text)) {
						popupTemp.error("请定位商品自提的地址")
						return true
					}
				}

				// 校验商品原价
				if (service.check.isNumber(goods.originalPrice)) {
					if (goods.originalPrice.toString().includes(".")) {
						if (service.check.isDecimalOutBounds(goods.originalPrice, 2)) {
							popupTemp.error("商品原价最大精确到分(小数点最多两位)")
							return true
						}
					}
					if (goods.originalPrice <= 0) {
						popupTemp.error("商品价格必须大于 0 元")
						return true
					}
				} else {
					popupTemp.error("商品原价请输入数字")
					return true
				}

				// 校验商品库存
				if (goods.inventory < -1 || service.check.isNull(goods.inventory)) {
					popupTemp.error("商品库存参数错误")
					return true
				}

				// 校验商品单位
				if (service.check.isNull(goods.unit)) {
					popupTemp.error("请输入商品售卖单位")
					return true
				}


				// 如果开启了固定购买数量 则校验 是否添加
				if (goods.buyUnit.open && goods.buyUnit.value.length === 0) {
					popupTemp.error("请添加固定的购买数量选项")
					return true
				}

				// 校验推广佣金
				if (service.check.isNumber(goods.commission)) {
					if (goods.commission.toString().includes(".")) {
						if (service.check.isDecimalOutBounds(goods.commission, 2)) {
							popupTemp.error("推广佣金最大精确到分(两位小数)")
							return true
						}
					}
					if (goods.commission < 0) {
						popupTemp.error("推广佣金至少为 0 元")
						return true
					}
				} else {
					popupTemp.error("推广佣金请输入数字")
					return true
				}

				// 校验无规格 售卖优惠
				if (goods.spec.has === -1) {
					// 判断是否填写了至少一个规格
					if (goods.spec.nList.length === 0) {
						popupTemp.error("请填写商品的优惠档位")
						return true;
					}
					let arr = service.copy(goods.spec.nList);

					// 校验优惠价格参数是否合法
					for (let i = 0; i < arr.length; i++) {
						if (service.check.isNumber(arr[i].discountPrice)) {
							if (arr[i].discountPrice.toString().includes(".")) {
								if (service.check.isDecimalOutBounds(arr[i].discountPrice, 2)) {
									popupTemp.error("请检查拼团参数, 拼团优惠价最大精确到分(两位小数)")
									return true
								}
							}
							if (arr[i].discountPrice <= 0) {
								popupTemp.error("请检查拼团参数, 拼团优惠价至少大于 0 元")
								return true
							}
						} else {
							popupTemp.error("请检查拼团参数, 存在不是数字的拼团优惠价")
							return true
						}
					}

					arr.sort((a, b) => b.successGear - a.successGear);
					// 校验最优惠挡位 优惠价 超过或等于 原价
					if (parseFloat(arr[0].discountPrice) >= goods.originalPrice) {
						popupTemp.error("拼团优惠价必须小于原价")
						return true;
					}
					// 判断最大需求库存 是否超过 商品原库存
					if (goods.inventory !== -1 && parseInt(arr[0].successGear) > goods.inventory) {
						popupTemp.error("拼团优惠档位所需要达到的购买数量,不能超过商品原库存数量")
						return true
					}
					for (let i = 1; i < arr.length && arr.length >= 1; i++) {
						if (parseFloat(arr[i].discountPrice) <= arr[i - 1].discountPrice) {
							popupTemp.error("高挡位优惠价必须小于低档位优惠价")
							return true;
						}
					}
				} else {
					/* 校验有规格售卖单位 */
					if (goods.spec.yList.length === 0) {
						popupTemp.error("请填写商品优惠规格")
						return true;
					}
					let arr = service.copy(goods.spec.yList);
					for (let i = 0; i < arr.length; i++) {

						if (service.check.isNull(arr[i].specName)) {
							popupTemp.error("请检查商品规格 , 规格名称不能为空")
							return true;
						}

						if (arr[i].inventory < -1 || arr[i].inventory === 0) {
							popupTemp.error("规格名 : " + arr[i].specName + " 库存量不能小于 -1 不能等于 0")
							return true;
						}

						// 校验规格原价合法
						if (service.check.isNumber(arr[i].originalPrice)) {
							if (arr[i].originalPrice.toString().includes(".")) {
								if (service.check.isDecimalOutBounds(arr[i].originalPrice, 2)) {
									popupTemp.error("规格名 : " + arr[i].specName + " , 规格原价最大精确到分(两位小数)")
									return true
								}
							}
							if (arr[i].originalPrice <= 0) {
								popupTemp.error("规格名 : " + arr[i].specName + " , 规格原价至少大于 0 元")
								return true
							}
						} else {
							popupTemp.error("规格名 : " + arr[i].specName + " , 存在不是数字的规格原价")
							return true
						}


						if (arr[i].priceGear.length === 0) {
							popupTemp.error("规格名 : " + arr[i].specName + " 该规格优惠档位不能为空")
							return true;
						}

						// 多个规格校验名称不相同
						if (arr.length !== 1) {
							let temp = service.copy(arr)
							temp.splice(i, 1);
							if (temp.some(e => e.specName === arr[i].specName)) {
								popupTemp.error("存在相同的规格名,请修改")
								return true;
							}
						}

						// 得到当前规格优惠挡位
						let arr2 = service.copy(arr[i].priceGear);


						for (let j = 0; j < arr2.length; j++) {
							if (service.check.isNumber(arr2[i].discountPrice)) {
								if (arr2[i].discountPrice.toString().includes(".")) {
									if (service.check.isDecimalOutBounds(arr2[i].discountPrice, 2)) {
										popupTemp.error("规格名 : " + arr[i].specName + " , 拼团优惠价最大精确到分(两位小数)")
										return true
									}
								}
								if (arr2[i].discountPrice <= 0) {
									popupTemp.error("规格名 : " + arr[i].specName + " , 拼团优惠价至少大于 0 元")
									return true
								}
							} else {
								popupTemp.error("规格名 : " + arr[i].specName + " , 存在不是数字的拼团优惠价")
								return true
							}
						}

						// 按优惠挡位逆序
						arr2.sort((a, b) => b.successGear - a.successGear);

						// 判断当前优惠价格是否超过或等于 原价
						if (parseFloat(arr2[0].discountPrice) >= parseFloat(arr[i].originalPrice)) {
							popupTemp.error("规格名 : " + arr[i].specName + " 该规格中的某档位优惠价超过了该规格原价")
							return true;
						}


						if (arr[i].inventory !== -1 && arr2[0].successGear > arr[i].inventory) {
							popupTemp.error("规格名 : " + arr[i].specName + "该规格中的某优惠挡位需要达到的购买数量,超过了该规格库存")
							return true;
						}

						for (let j = 1; j < arr2.length && arr2.length >= 1; j++) {
							if (parseFloat(arr2[j].discountPrice) <= parseFloat(arr2[j - 1].discountPrice)) {
								popupTemp.error("规格名 : " + arr[i].specName + " 该规格中高挡位优惠价必须小于低档位优惠价")
								return true;
							}
						}

					}
				}
				console.log("参数通过校验....")
				return false;
			},
			/* 获取添加请求对象 */
			getAddRequest() {
				let goods = service.copy(this.goods);
				// 处理轮播图
				let img = [];
				goods.img.list.forEach(e => img.push(e.base64))
				// 处理优惠挡位
				let priceList = goods.spec.has === 1 ?
					JSON.stringify(goods.spec.yList) : JSON.stringify(goods.spec.nList);
				// 处理限购地区列表
				let areaList = goods.limitArea.has === -1 ? '' : service.arrToString(goods.limitArea.idList, ',');
				// 删除富文本中的 域名
				goods.content = goods.content.replace(this.imgApi, "");

				let data = {
					title: goods.title,
					categoryId: goods.category.id,
					// avatar: goods.avatar.list[0].base64,
					img: JSON.stringify(img),
					overview: goods.overview,
					content: goods.content,
					inventory: goods.inventory,
					urlId: goods.urlId,
					originalPrice: goods.originalPrice,
					hasSpec: goods.spec.has,
					startTime: goods.time.value[0],
					endTime: goods.time.value[1],
					commission: goods.commission,
					freightId: goods.freightId,
					unit: goods.unit,
					buyUnit: goods.buyUnit.open ? service.arrToString(goods.buyUnit.value, ',') : '',
					priceList: priceList,
					areaList: areaList,
					type: goods.type,
					selfMentionAddress: goods.selfMentionAddress.text,
					latLng: goods.selfMentionAddress.lat + "," + goods.selfMentionAddress.lng,
					hasFreeShipping: goods.hasFreeShipp,
					locationIds: goods.locationIds.list.length === 0 ? '' : service.arrToString(goods.locationIds.list,
						','),
					isAutoShelving: goods.isAutoShelving,
					app: "wx"
				}
				if (goods.isAutoShelving === 1) {
					data.autoShelvingTime = goods.autoShelvingTime;
				}
				return data;
			},
			/* 获取修改请求对象 */
			getUpdateRequest() {
				let _t = this;
				let goods = service.copy(this.goods);
				// 处理轮播图
				let img = [];
				goods.img.list.forEach(e => {
					if (!service.check.isNull(e.base64)) {
						img.push(e.base64)
					} else if (!service.check.isNull(e.url)) {
						img.push(e.url.replace(_t.imgApi, ""))
					}

				})
				// 处理优惠挡位
				let priceList = goods.spec.has === 1 ?
					JSON.stringify(goods.spec.yList) : JSON.stringify(goods.spec.nList);
				// 处理限购地区列表
				let areaList = goods.limitArea.has === -1 ? '' : service.arrToString(goods.limitArea.idList, ',')
				// 删除富文本中的 域名
				goods.content = goods.content.replace(this.imgApi, "");
				let data = {
					id: goods.id,
					title: goods.title,
					categoryId: goods.category.id,
					avatar: service.check.isNull(goods.avatar.list[0].base64) ? '' : goods.avatar.list[0].base64,
					img: JSON.stringify(img),
					overview: goods.overview,
					content: goods.content,
					inventory: goods.inventory,
					originalPrice: goods.originalPrice,
					hasVideo: goods.video.hasUpdate.toString(),
					hasSpec: goods.spec.has,
					startTime: goods.time.value[0],
					endTime: goods.time.value[1],
					commission: service.check.isNull(goods.commission) ? 0 : goods.commission,
					freightId: goods.freightId,
					unit: goods.unit,
					buyUnit: goods.buyUnit.open ? service.arrToString(goods.buyUnit.value, ',') : '',
					priceList: priceList,
					areaList: areaList,
					type: goods.type,
					selfMentionAddress: goods.selfMentionAddress.text,
					latLng: goods.selfMentionAddress.lat + "," + goods.selfMentionAddress.lng,
					hasFreeShipping: goods.hasFreeShipp,
					locationIds: goods.locationIds.list.length === 0 ? '' : service.arrToString(goods.locationIds.list,
						','),
					isAutoShelving: goods.isAutoShelving,
					app: "wx"
				}
				if (goods.isAutoShelving === 1) {
					data.autoShelvingTime = goods.autoShelvingTime;
				}
				return data;
			},
		},
		onLoad(e) {
			wx.enableAlertBeforeUnload({
				message: "确定退出当前页面吗？您编辑的商品内容将不会保留",
				success: function(res) {
					console.log("成功：", res);
				},
				fail: function(err) {
					console.log("失败：", err);
				},
			});
			// 获取图像地址前缀
			this.imgApi = this.$reqConfig.URLIMAGE
			// 获取请求头类型
			this.contentType = this.$reqConfig.CONTENTTYPE + ";+charset=UTF-8"
			// 获取token
			this.token = uni.getStorageSync("merchantsToken").token
			uni.showLoading({
				title: '加载中',
				mask: true
			});

			// 设置需要等待的请求数量
			this.loading.threshold = 3;
			// 不是跳转不解析
			if (typeof e !== "undefined" && typeof e.param !== "undefined") {
				// 存下路由传递的值
				this.routerV = JSON.parse(e.param);
				console.log("传过来的数据 : ", e.param)
				// 判断跳转到此页面目的是否为修改
				if (this.routerV.target === 'update' && !this.check.isNull(this.routerV.goodsId)) {
					// 需要回显步进+1
					this.loading.threshold++;
					this.getDetails(this.routerV.goodsId);
					this.target = 'update';
				} else {
					// 如果是添加那么打开地图定位 当前定位
					this.goods.selfMentionAddress.lat = uni.getStorageSync("dingwei").latitude
					this.goods.selfMentionAddress.lng = uni.getStorageSync("dingwei").longitude
					if (typeof this.goods.selfMentionAddress.lat === "undefined" ||
						typeof this.goods.selfMentionAddress.lng === 'undefined') {
						let t = this;
						service.getLocation(t, {
							ok: function(t, res) {
								t.goods.selfMentionAddress.lat = res.latitude;
								t.goods.selfMentionAddress.lng = res.longitude;
								uni.setStorageSync({
									key: 'dingwei',
									data: {
										longitude: res.longitude,
										latitude: res.latitude,
									},
								});
							}
						})
					}
				}
			}

			// 获取商品分类选项
			this.getCategoryOptions();
			// 获取地址分类树
			this.getLocationTree();
			// 获取商家运费模板
			this.getMerchantFreightTemplate()

		},
	}
</script>

<style scope lang="scss">
	.topBack {
		position: fixed;
		z-index: 999;
		right: 35rpx;
		bottom: 200rpx;
	}

	/deep/.head.data-v-52732d16 {
		width: 55% !important;
	}

	/deep/ .uni-section__content-title.data-v-5584ec96 {
		font-size: 34rpx !important;
	}

	/deep/.head .btn.right.data-v-52732d16 {
		color: white;
		background-color: #1e90ff;
	}

	/*标题分割线样式*/
	/deep/ .line.data-v-5584ec96 {
		height: 15px;
		background-color: #0dd8ae !important;
		border-radius: 5px;
		width: 7px !important;
	}

	/*表单 label*/
	.u-form-item__body__left__content__label.data-v-067e4733 {
		font-size: 30rpx;
		font-weight: bold;
	}

	#editor {
		width: 100%;
		height: 300px;
		background-color: #CCCCCC;
		z-index: 1000
	}

	/*表单错误提示样式*/
	/deep/ .u-form-item__body__right__message.data-v-067e4733 {
		font-size: 30rpx !important;
		font-weight: bold !important;
	}

	/*表单下划线*/
	.u-line.data-v-727e452e {
		border-bottom-width: 8rpx !important;
	}

	.u-textarea.data-v-09988a29 {
		background-color: #fff0 !important;
	}

	.my-tag {
		z-index: 1 !important;
	}
</style>
